package guoanmaker.operator.business.service;

import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import guoanmaker.operator.business.dao.OperatorContractDao;
import guoanmaker.operator.business.dao.OperatorContractDemandDao;
import guoanmaker.operator.business.model.OperatorContract;
import guoanmaker.operator.business.model.OperatorContractDemand;
import guoanmaker.operator.business.model.OperatorContractDownloadCount;
import guoanmaker.operator.business.model.OperatorContractDownloadLog;
import guoanmaker.operator.business.model.OperatorContractType;
import guoanmaker.operator.business.model.OperatorMailConfig;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.modelnobind.OperatorContractBind;
import guoanmaker.operator.business.modelnobind.OperatorContractDemandBind;
import guoanmaker.operator.business.modelnobind.OperatorContractDownloadCountBind;
import guoanmaker.operator.business.repository.OperatorContractDemandRepository;
import guoanmaker.operator.business.repository.OperatorContractDownloadCountRepository;
import guoanmaker.operator.business.repository.OperatorContractDownloadLogRepository;
import guoanmaker.operator.business.repository.OperatorContractRepository;
import guoanmaker.operator.business.repository.OperatorContractTypeRepository;
import guoanmaker.operator.business.repository.OperatorMailConfigRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;

/**
 * 
* @ClassName: OperatorContractService 
* @Description: TODO(合同操作类) 
* @author (ZhangXinYu)  
* @date 2017年12月17日 上午11:20:58 
* @version V1.0
 */
@Service
public class OperatorContractService implements OperatorContractServiceInterface {

	@Autowired
	private OperatorContractTypeRepository operatorContractTypeRepository;
	@Autowired
	private OperatorContractRepository operatorContractRepository;
	@Autowired
	private OperatorContractDemandRepository operatorContractDemandRepository;
	@Autowired
	private OperatorContractDao operatorContractDao;
	@Autowired
	private OperatorContractDemandDao operatorContractDemandDao;
	@Autowired
	private OperatorMailConfigRepository operatorMailConfigRepository;
	@Autowired
	private OperatorContractDownloadCountRepository contractDownloadCountRepository;
	@Autowired
	private OperatorContractDownloadLogRepository contractDownloadLogRepository;
	@Autowired
	private PersonalUserRepository personalUserRepository;
	
	@PersistenceContext
	EntityManager em;
	
	/**
	 * 添加合同类型
	 * 0>>失败  1>>成功  2>>类型名称重复
	 */
	@Override
	public Integer addContractType(String type, String guide) {
		Integer result = 0;
		if(guide==null||guide.equals("")){
			List<OperatorContractType> contractTypes = operatorContractTypeRepository.findByNAndG(type);
			if(contractTypes != null && contractTypes.size() > 0){
				result = 2;
			}else{
				OperatorContractType contractType = new OperatorContractType();
				contractType.setName(type);
				contractType.setUseCount(0);
				contractType.setCreateDate(new Date());
				contractType = operatorContractTypeRepository.save(contractType);
				result = contractType == null ? 0 : 1;
			}
		}else{
			List<OperatorContractType> contractTypes = operatorContractTypeRepository.findByNameAndGuideEquals(type,"1");
			if(contractTypes != null && contractTypes.size() > 0){
				result = 2;
			}else{
				OperatorContractType contractType = new OperatorContractType();
				contractType.setName(type);
				contractType.setUseCount(0);
				contractType.setGuide("1");
				contractType.setCreateDate(new Date());
				contractType = operatorContractTypeRepository.save(contractType);
				result = contractType == null ? 0 : 1;
			}
		}
		return result;
	}

	/**
	 * 查询所有合同类型
	 */
	@Override
	public List<OperatorContractType> contractTypes1(String guide) {
		//return operatorContractTypeRepository.findAll();
		List<OperatorContractType>  list=null;
		if(guide==null||guide.equals("")){
			Specification<OperatorContractType> specification=new Specification<OperatorContractType>() {
				@Override
				public Predicate toPredicate(Root<OperatorContractType> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
					List<Predicate> lstPredicates = new ArrayList<Predicate>();
					Predicate p1=criteriaBuilder.isNull(root.get("guide"));
					lstPredicates.add(criteriaBuilder.or(p1));
					Predicate p2=criteriaBuilder.equal(root.get("guide"), "");
					lstPredicates.add(criteriaBuilder.or(p2));
					Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
					return criteriaBuilder.or(lstPredicates.toArray(arrayPredicates));
				}
			};
			Sort sort = new Sort(Sort.Direction.DESC, "createDate");
			list= operatorContractTypeRepository.findAll(specification,sort);
		}else{
			Specification<OperatorContractType> specification=new Specification<OperatorContractType>() {
				@Override
				public Predicate toPredicate(Root<OperatorContractType> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
					List<Predicate> lstPredicates = new ArrayList<Predicate>();
					if(StringUtils.isNotEmpty(guide)){
						lstPredicates.add(criteriaBuilder.equal(root.get("guide"), "1"));
					}
					Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
					return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
				}
			};
			Sort sort = new Sort(Sort.Direction.DESC, "createDate");
			list= operatorContractTypeRepository.findAll(specification,sort);
		}
		return list;
	}

	/**
	 * 查询所有合同类型
	 */
	@Override
	public List<OperatorContractType> contractTypes2(String name,String guide) {
		if(guide==null||guide.equals("")){
			if(name != null && !name.equals(""))
				return operatorContractTypeRepository.findByNameLikeAndGuideNotOrderByCreateDateDesc(name);
			else{
				Specification<OperatorContractType> specification=new Specification<OperatorContractType>() {
					@Override
					public Predicate toPredicate(Root<OperatorContractType> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
						List<Predicate> lstPredicates = new ArrayList<Predicate>();
						Predicate p1=criteriaBuilder.isNull(root.get("guide"));
						lstPredicates.add(criteriaBuilder.or(p1));
						Predicate p2=criteriaBuilder.equal(root.get("guide"), "");
						lstPredicates.add(criteriaBuilder.or(p2));
						Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
						return criteriaBuilder.or(lstPredicates.toArray(arrayPredicates));
					}
				};
				Sort sort = new Sort(Sort.Direction.DESC, "createDate");
				return operatorContractTypeRepository.findAll(specification,sort);
			}
			
		}else{
			if(name != null && !name.equals(""))
				return operatorContractTypeRepository.findByNameLikeAndGuideEqualsOrderByCreateDateDesc("%"+name+"%","1");
			else{
				Specification<OperatorContractType> specification=new Specification<OperatorContractType>() {
					@Override
					public Predicate toPredicate(Root<OperatorContractType> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
						List<Predicate> lstPredicates = new ArrayList<Predicate>();
						if(StringUtils.isNotEmpty(guide)){
							lstPredicates.add(criteriaBuilder.equal(root.get("guide"), "1"));
						}
						Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
						return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
					}
				};
				Sort sort = new Sort(Sort.Direction.DESC, "createDate");
				return operatorContractTypeRepository.findAll(specification,sort);
			}
			
		}
		
	}
	
	/**
	 * 查询所有合同类型
	 */
	@Override
	public Map<String, Object>  contractTypes3(Integer currentPage , Integer PageSize,String guide) {
		
		return operatorContractDao.contractTypes(currentPage, PageSize, guide);
	}


	/**
	 * 编辑合同类型
	 * 0>>失败  1>>成功	2>>类型名称重复
	 */
	@Override
	public Integer editContractType(String id, String type) {
		Integer result = 0;
		List<OperatorContractType> contractTypes = operatorContractTypeRepository.findByNameAndIdNot(type,id);
		if(contractTypes != null && contractTypes.size() > 0){
			result = 2;
		}else{
			OperatorContractType contractType = operatorContractTypeRepository.findOne(id);
			if(contractType != null){
				contractType.setName(type);
				contractType = operatorContractTypeRepository.save(contractType);
				if (contractType != null) {
					result = 1;
					//合同类型修改  更改合同计量表中合同类型名称
					contractDownloadCountRepository.updateContractTypeName(contractType.getId(), contractType.getName());
				}
			}
		}
		return result;
	}

	/**
	 * 删除合同类型
	 * 0>>失败  1>>成功 2>>失败-合同类型使用中
	 */
	@Override
	public Integer deleteContractType(String id) {
		OperatorContractType operatorContractType = operatorContractTypeRepository.findOne(id);
		if(operatorContractType != null){
			if(operatorContractType.getUseCount() == 0){
				operatorContractTypeRepository.delete(operatorContractType);
			}else{
				return 2;
			}
		}
		else{
			return 0;
		}
		return 1;
	}

	/**
	 * 上传合同文件
	 * 0>>失败  1>>成功	2>>合同名称重复
	 */
	@Override
	@Transactional
	public Integer addContract(String name, String typeid, String fileUrl, String imgUrl,String guide) {
		Integer result = 0;
		if(guide==null||guide.equals("")){
			List<OperatorContractBind> contractBinds = operatorContractDao.findByName(name);
			if(contractBinds != null && contractBinds.size() > 0){
				//合同名称重复
				result = 2;
			}else{
				OperatorContractType contractType = operatorContractTypeRepository.findOne(typeid);
				if(contractType != null){
					OperatorContract contract = new OperatorContract();
					contract.setName(name);
					contract.setFile(fileUrl);
					contract.setImg(imgUrl);
					contract.setDate(new Date());
					contract.setContractType(contractType);
					contractType.getContracts().add(contract);
					contract = operatorContractRepository.save(contract);
					if(contract != null){
						//合同添加成功
						//合同类型使用数量++
						operatorContractTypeRepository.addContractTypeCount(typeid);
						result = 1;
						//合同添加成功后需要将合同添加到合同下载计量表中
						OperatorContractDownloadCount contractDownloadCount = new OperatorContractDownloadCount();
						contractDownloadCount.setContractId(contract.getId());
						contractDownloadCount.setContractName(contract.getName());
						contractDownloadCount.setTypeId(contractType.getId());
						contractDownloadCount.setTypeName(contractType.getName());
						contractDownloadCount.setCount(0);
						contractDownloadCount.setLastDate(new Date());
						contractDownloadCountRepository.save(contractDownloadCount);	//保存合同及计量信息
					}
				}
			}
			
		}else{
			List<OperatorContractBind> contractBinds = operatorContractDao.findByName1(name);
			if(contractBinds != null && contractBinds.size() > 0){
				//合同名称重复
				result = 2;
			}else{
				OperatorContractType contractType = operatorContractTypeRepository.findOne(typeid);
				if(contractType != null){
					OperatorContract contract = new OperatorContract();
					contract.setName(name);
					contract.setFile(fileUrl);
					contract.setImg(imgUrl);
					contract.setDate(new Date());
					contract.setGuide("1");
					contract.setContractType(contractType);
					contractType.getContracts().add(contract);
					contract = operatorContractRepository.save(contract);
					if(contract != null){
						//合同添加成功
						//合同类型使用数量++
						operatorContractTypeRepository.addContractTypeCount(typeid);
						result = 1;
						//合同添加成功后需要将合同添加到合同下载计量表中
						OperatorContractDownloadCount contractDownloadCount = new OperatorContractDownloadCount();
						contractDownloadCount.setContractId(contract.getId());
						contractDownloadCount.setContractName(contract.getName());
						contractDownloadCount.setTypeId(contractType.getId());
						contractDownloadCount.setTypeName(contractType.getName());
						contractDownloadCount.setCount(0);
						contractDownloadCount.setGuide("1");;
						contractDownloadCount.setLastDate(new Date());
						contractDownloadCountRepository.save(contractDownloadCount);	//保存合同及计量信息
					}
				}
			}
		}
		return result;
	}

	/**
	 * 查询所有合同信息
	 */
	@Override
	public Map<String, Object> findAllContract(String name , String typeid , Integer currentPage , Integer pageSize,String guide) {
		Map<String, Object> map = new HashMap<>();
		long count = operatorContractDao.findAllCount(name, typeid,guide);
		map.put("totalCount", count);
		count = count % pageSize == 0 ? count /pageSize : count /pageSize + 1;
		map.put("totalPage", count);
		List<OperatorContractBind> contractBinds = operatorContractDao.findAll(name, typeid,currentPage , pageSize,guide);
		for (OperatorContractBind contractBind : contractBinds) {
			String filename = contractBind.getName();
			String urlstr = contractBind.getFile();
			filename += urlstr.substring(0,urlstr.indexOf('?')).substring(urlstr.substring(0,urlstr.indexOf('?')).lastIndexOf("."));
			contractBind.setName(filename);
		}
		map.put("contracts", contractBinds);
		return map;
	}

	/**
	 *  查询指定合同信息
	 */
	@Override
	public OperatorContractBind findContractById(String id) {
		return operatorContractDao.findContractInfo(id);
	}

	/**
	 * 编辑合同
	 * 0>>失败 1>>成功 2>>合同名称重复
	 */
	@Override
	public Integer editContract(String id, String name, String typeid, String file, String img) {
		Integer result = 0;
		List<OperatorContractBind> contractBinds = operatorContractDao.findByNameAndIdNot(name, id);
		if(contractBinds != null && contractBinds.size() > 0){
			//合同名称重复
			result =2;
		}else{
			OperatorContract operatorContract = operatorContractRepository.findOne(id);
			if(operatorContract != null){
				operatorContract.setName(name);
				operatorContract.setFile(file);
				operatorContract.setImg(img);
				operatorContract.setDate(new Date());
				//System.out.println(operatorContract.getContractType().getId());
				OperatorContractType old_contractType = operatorContractTypeRepository.findOne(operatorContract.getContractType().getId());
				OperatorContractType contractType = operatorContractTypeRepository.findOne(typeid);
				if(operatorContract!=null && old_contractType != null){
					old_contractType.getContracts().remove(operatorContract);
					contractType.getContracts().add(operatorContract);
					operatorContract.setContractType(contractType);
					operatorContract = operatorContractRepository.save(operatorContract);
					if (operatorContract != null) {
						//减少原合同类型使用数量
						operatorContractTypeRepository.divContractTypeCount(old_contractType.getId());
						// 增加新合同类型使用数量
						operatorContractTypeRepository.addContractTypeCount(typeid);
						result = 1;
						
						//合同修改成功后需要对合同计量表名称进行更新
						contractDownloadCountRepository.updateContractName(operatorContract.getId(), operatorContract.getName());
					}
				}
			}
		}
		return result;
	}

	/**
	 * 删除合同
	 * 0>>失败  1>>成功
	 */
	@Override
	public Integer removeContract(String id) {
		Integer result = 0;
		OperatorContract operatorContract = operatorContractRepository.findOne(id);
		if(operatorContract != null){
			operatorContractRepository.delete(operatorContract);
			operatorContractTypeRepository.divContractTypeCount(operatorContract.getContractType().getId());
			result = 1;
		}
		return result;
	}

	/**
	 * 添加合同需求
	 * 0>>失败   1>>成功	2>>类型/合同名重复
	 */
	@Override
	public Integer addContractDemand(String type, String name, String email) {
		Integer result = 0;
		/*List<OperatorContractDemandBind> contractBinds = operatorContractDemandDao.findContractDemand(name, null, null, 0,10);
		List<OperatorContractType> contractTypes = operatorContractTypeRepository.findByName(type);
		if(contractBinds != null && contractBinds.size() > 0){
			result = 2;
		}else if(contractTypes != null && contractTypes.size() > 0){
			result = 2;
		}else{
		}*/
		OperatorContractDemand contractDemand = new OperatorContractDemand();
		contractDemand.setType(type);
		contractDemand.setName(name);
		contractDemand.setEmail(email);
		contractDemand.setDate(new Date());
		contractDemand = operatorContractDemandRepository.save(contractDemand);
		if(contractDemand != null){
			result = 1;
		}
		return result;
	}

	/**
	 * 移除合同需求
	 * 0>>失败  1>>成功
	 */
	@Override
	public Integer removeContractDemand(String id) {
		Integer result = 0;
		OperatorContractDemand contractDemand = operatorContractDemandRepository.findOne(id);
		if(contractDemand != null){
			operatorContractDemandRepository.delete(contractDemand);
			result = 1;
		}
		return result;
	}

	/**
	 * 查询合同需求
	 */
	@Override
	public Map<String, Object> findContractDemand(String name, String startDate, String endDate, Integer currentPage, Integer pageSize) {
		Map<String, Object> map = new HashMap<>();
		long count = operatorContractDemandDao.findContractDemandCount(name, startDate, endDate);
		map.put("totalCount", count);
		count = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
		map.put("totalPage", count);
		List<OperatorContractDemandBind> contractDemandBinds = operatorContractDemandDao.findContractDemand(name, startDate, endDate, currentPage ,pageSize);
		map.put("contractDemands", contractDemandBinds);
		return map;
	}

	/**
	 * 查询合同类型总数
	 */
	@Override
	public int contractTypeCount(String guide) {
		int a=0;
		if(guide==null||guide.equals("")){
			a=operatorContractTypeRepository.selectByGuidenotEquals();
		}else{
			a=operatorContractTypeRepository.selectByGuideEquals();
		}
		return a;
		//return operatorContractTypeRepository.count();
	}

	/**
	 * 发送邮件 
	 * 0>>失败 1>>成功
	 */
	@Transactional
	@Override
	public Integer sendMail(String userId,String address, String ids,String guide) throws Exception{
		Integer result = 0;
		List<OperatorMailConfig> operatorMailConfigs= operatorMailConfigRepository.findAll();
		OperatorMailConfig operatorMailConfig=operatorMailConfigs.get(0);
		//Main main =new Main();
		//main.mail(operatorMailConfig.getAccount(),operatorMailConfig.getPassword(),address,"合同文件下载","测试内容");
		
		String myEmailAccount=operatorMailConfig.getAccount().trim();
    	
    	Properties props = new Properties();                    // 参数配置
       
    	String myEmailSMTPHost="";
    	boolean res=operatorMailConfig.getAccount().trim().contains("@qq");
    	if(res){
    		myEmailSMTPHost = "smtp.qq.com";
    		 final String smtpPort = "465";
    	        props.setProperty("mail.smtp.port", smtpPort);
    	        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    	        props.setProperty("mail.smtp.socketFactory.fallback", "false");
    	        props.setProperty("mail.smtp.socketFactory.port", smtpPort);
    	        props.setProperty("mail.smtp.ssl.enable", "true");
    	}
    	
    	boolean res163=operatorMailConfig.getAccount().trim().contains("@163");
    	if(res163){
    		myEmailSMTPHost = "smtp.163.com";
    	}
    	
    	boolean resgakj=operatorMailConfig.getAccount().trim().contains("@gakj");
    	if(resgakj){
    		myEmailSMTPHost = "mail.gakj.citic.com";
    	}
    	
    	 props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
         props.setProperty("mail.smtp.host", myEmailSMTPHost);   // 发件人的邮箱的 SMTP 服务器地址
         props.setProperty("mail.smtp.auth", "true");            // 需要请求认证

        // 2. 根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);                                 // 设置为debug模式, 可以查看详细的发送 log

        // 3. 创建一封邮件
        //MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount,title,content,receiveMailAccount);
        /*****/
	        // 1. 创建一封邮件
	        MimeMessage message = new MimeMessage(session);
	
	        // 2. From: 发件人（昵称有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改昵称）
	        message.setFrom(new InternetAddress(operatorMailConfig.getAccount(), "国安创客", "UTF-8"));
	
	        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
	        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(address, address+"用户", "UTF-8"));
	
	        // 4. Subject: 邮件主题（标题有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改标题）
	        if(guide==null||guide.equals("")){
	        	message.setSubject("合同文件下载", "UTF-8");
	        }else{
	        	message.setSubject("文件下载", "UTF-8");
	        }
	        // 5. Content: 邮件正文（可以使用html标签）（内容有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改发送内容）
	        //message.setContent(content, "text/html;charset=UTF-8");
	        String[] contractIds = ids.split(";");
	        MimeMultipart allPart = new MimeMultipart("mixed");
	        for (String id : contractIds) {
				OperatorContractBind contractBind = operatorContractDao.findContractInfo(id);
				if(contractBind != null){
					MimeBodyPart attachment = createAttachment("("+contractBind.getTypename()+")"+contractBind.getName(),contractBind.getFile());
		        	allPart.addBodyPart(attachment);
				}
			}
	        //邮件正文
	        /*String body = "<style>body{margin:0px;padding: 0px} p{text-indent:2em} img{height: 250px;width: 250px} #left_div{float: left;width: 50%;height: 300px;text-align: center;} #right_div{float: right;width: 50%;height: 280px;text-align: center;margin-bottom: 20px}</style>"; 
	        body += "<div><span>尊敬的用户</span>";
	        body += "<p>感谢您使用国安创客下载合同模板，国安创客（北京）科技有限公司（简称“国安创客”） 在中信集团、国安集团双品牌背书支持下成立，致力于服务创新型的中小微企业。在国家“大众创业，万众创新”的大背景下，国安创客整合集团的优势产业资源，聚集社会资源，形成全要素、立体化的企业服务平台。为满足大众创业者最为迫切的资金、场地、市场、扶持与成长等需求，国安创客为中小微企业提供包括金融服务、空间租赁、营销服务、工商服务、知识产权服务、网络服务、培训服务等全方位支持，全面满足企业发展生命周期所需。</p>";
	        body += "<p>衷心地希望此合同模板能够满足您的需求，如果需要更多服务，请及时联络我们。</p> ";
			body += "客服热线：400-851-8585<br/>";
			body += "官方网站：<a href='http://www.gack.citic'>www.gack.citic</a></div>";
			body += "<div id='left_div'><span>微信号：</span><br/><img id='img1' src='https://guoanchuangke2.oss-cn-beijing.aliyuncs.com/datas/contractImg/1515032742721.png?Expires=4668631805&OSSAccessKeyId=LTAILWi7cyx4nHeI&Signature=nDCntPoA149QWQfX4aHufNIsCuk%3D'/></div>";
			body += "<div id='right_div'><span>app下载</span><br/><img id='img2' src='https://guoanchuangke2.oss-cn-beijing.aliyuncs.com/datas/contractImg/1515032718143.png?Expires=4668631853&OSSAccessKeyId=LTAILWi7cyx4nHeI&Signature=zj2H3lbicvhe14B3F5LcqmPTw%2BQ%3D'/></div>";*/
	        /*String body = "<style>body{margin:0px;padding: 0px} p{text-indent:2em} img{height: 250px;width: 250px} #span_1{float: left;margin-left: 25%} #span_2{margin-left: 35%} #img_1{float: left;margin-left: 20%} #img_2{margin-left: 20%}</style>"; 
	        body += "<span>尊敬的用户</span>";
	        body += "<p>感谢您使用国安创客下载合同模板，国安创客（北京）科技有限公司（简称“国安创客”） 在中信集团、国安集团双品牌背书支持下成立，致力于服务创新型的中小微企业。在国家“大众创业，万众创新”的大背景下，国安创客整合集团的优势产业资源，聚集社会资源，形成全要素、立体化的企业服务平台。为满足大众创业者最为迫切的资金、场地、市场、扶持与成长等需求，国安创客为中小微企业提供包括金融服务、空间租赁、营销服务、工商服务、知识产权服务、网络服务、培训服务等全方位支持，全面满足企业发展生命周期所需。</p>";
	        body += "<p>衷心地希望此合同模板能够满足您的需求，如果需要更多服务，请及时联络我们。</p> ";
			body += "客服热线：400-851-8585<br/>";
			body += "官方网站：<a href='http://www.gack.citic'>www.gack.citic</a><br/>";
			body += "<span id='span_1'>微信号：</span><span id='span_2'>app下载</span><br/>";
			body += "<img id='img_1' src='https://guoanchuangke2.oss-cn-beijing.aliyuncs.com/datas/contractImg/1515032742721.png?Expires=4668631805&OSSAccessKeyId=LTAILWi7cyx4nHeI&Signature=nDCntPoA149QWQfX4aHufNIsCuk%3D'/>";
			body += "<img id='img_2' src='https://guoanchuangke2.oss-cn-beijing.aliyuncs.com/datas/contractImg/1515032718143.png?Expires=4668631853&OSSAccessKeyId=LTAILWi7cyx4nHeI&Signature=zj2H3lbicvhe14B3F5LcqmPTw%2BQ%3D'/>";*/
	        String body = "<style>body{margin:0px;padding: 0px} p{text-indent:2em} img{height: 250px;width: 250px} #left_span{float: left;width: 50%;} #right_span{width: 50%;height: 320px; }</style>"; 
	        body += "<span>尊敬的用户</span>";
	        if(guide==null||guide.equals("")){
	        	body += "<p>感谢您使用国安创客下载合同模板，国安创客（北京）科技有限公司（简称“国安创客”） 在中信集团、国安集团双品牌背书支持下成立，致力于服务创新型的中小微企业。在国家“大众创业，万众创新”的大背景下，国安创客整合集团的优势产业资源，聚集社会资源，形成全要素、立体化的企业服务平台。为满足大众创业者最为迫切的资金、场地、市场、扶持与成长等需求，国安创客为中小微企业提供包括金融服务、空间租赁、营销服务、工商服务、知识产权服务、网络服务、培训服务等全方位支持，全面满足企业发展生命周期所需。</p>";
	        	body += "<p>衷心地希望此合同模板能够满足您的需求，如果需要更多服务，请及时联络我们。</p> ";
	        }else{
	        	body += "<p>感谢您使用国安创客下载办事指南模板，国安创客（北京）科技有限公司（简称“国安创客”） 在中信集团、国安集团双品牌背书支持下成立，致力于服务创新型的中小微企业。在国家“大众创业，万众创新”的大背景下，国安创客整合集团的优势产业资源，聚集社会资源，形成全要素、立体化的企业服务平台。为满足大众创业者最为迫切的资金、场地、市场、扶持与成长等需求，国安创客为中小微企业提供包括金融服务、空间租赁、营销服务、工商服务、知识产权服务、网络服务、培训服务等全方位支持，全面满足企业发展生命周期所需。</p>";
	        	body += "<p>衷心地希望此办事指南模板能够满足您的需求，如果需要更多服务，请及时联络我们。</p> ";
	        }
			body += "客服热线：400-851-8585<br/>";
			body += "官方网站：<a href='http://www.gack.citic'>www.gack.citic</a><br/>";
			body += "<span id='left_span'><center><span>微信号：</span><br/><img id='img1' src='https://guoanchuangke2.oss-cn-beijing.aliyuncs.com/datas/contractImg/1515032742721.png?Expires=4668631805&OSSAccessKeyId=LTAILWi7cyx4nHeI&Signature=nDCntPoA149QWQfX4aHufNIsCuk%3D'/></center></span>";
			body += "<span id='right_span'><center><span>app下载</span><br/><img id='img2' src='https://guoanchuangke2.oss-cn-beijing.aliyuncs.com/datas/contractImg/1515032718143.png?Expires=4668631853&OSSAccessKeyId=LTAILWi7cyx4nHeI&Signature=zj2H3lbicvhe14B3F5LcqmPTw%2BQ%3D'/></center></span>";
	        // 用于保存最终正文部分  
	        MimeBodyPart contentBody = new MimeBodyPart();  
	        // 用于组合文本和图片，"related"型的MimeMultipart对象  
	        MimeMultipart contentMulti = new MimeMultipart("related");  
	        // 正文的图片部分  
	        //MimeBodyPart jpgBody = new MimeBodyPart();  
	        //FileDataSource fds = new FileDataSource(fileName);  
	        //jpgBody.setDataHandler(new DataHandler(fds));  
	        //jpgBody.setContentID("logo_jpg");  
	        //contentMulti.addBodyPart(jpgBody);
	        // 正文的文本部分  
	        MimeBodyPart textBody = new MimeBodyPart();  
	        textBody.setContent(body, "text/html;charset=utf-8");  
	        contentMulti.addBodyPart(textBody);
	        contentBody.setContent(contentMulti);
	        allPart.addBodyPart(contentBody);
	        message.setContent(allPart);
	        
	        // 6. 设置发件时间
	        message.setSentDate(new Date());
	
	        // 7. 保存设置
	        message.saveChanges();
        /****/

        // 也可以保持到本地查看
        // message.writeTo(file_out_put_stream);

        // 4. 根据 Session 获取邮件传输对象
        Transport transport = session.getTransport();

        // 5. 使用 邮箱账号 和 密码 连接邮件服务器
        //    这里认证的邮箱必须与 message 中的发件人邮箱一致，否则报错
        transport.connect(myEmailAccount, operatorMailConfig.getPassword());

        // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());

        // 7. 关闭连接
        transport.close();
        result =1;
        
        //合同发送成功后		记录用户合同模板下载记录
        PersonalUser user = personalUserRepository.findOne(userId);
        if(user != null){
        	if(guide==null||guide.equals("")){
        		for (String contractId : contractIds) {
            		//下载多个文件时  循环添加多条记录
            			OperatorContractDownloadLog contractDownloadLog = new OperatorContractDownloadLog();
            			contractDownloadLog.setUser(user);
            			user.getDownloadLogs().add(contractDownloadLog);	//设置下载用户
            			contractDownloadLog.setDate(new Date());	//设置下载日期
            			OperatorContractDownloadCount contractDownloadCount = contractDownloadCountRepository.findByContractId(contractId).get(0);
            			contractDownloadLog.setDownloadId(contractDownloadCount.getId());	//设置下载id
            			//保存下载记录
            			contractDownloadLogRepository.save(contractDownloadLog);
            			//下载文件计量+1
            			contractDownloadCount.setCount(contractDownloadCount.getCount()+1);
            			contractDownloadCount.setLastDate(new Date());
            			contractDownloadCountRepository.save(contractDownloadCount);
            		
    			}
        		
    		}else{
    			for (String contractId : contractIds) {
            		//下载多个文件时  循环添加多条记录
            			OperatorContractDownloadLog contractDownloadLog = new OperatorContractDownloadLog();
            			contractDownloadLog.setUser(user);
            			user.getDownloadLogs().add(contractDownloadLog);	//设置下载用户
            			contractDownloadLog.setDate(new Date());	//设置下载日期
            			contractDownloadLog.setGuide("1");
            			OperatorContractDownloadCount contractDownloadCount = contractDownloadCountRepository.findByContractId(contractId).get(0);
            			contractDownloadLog.setDownloadId(contractDownloadCount.getId());	//设置下载id
            			//保存下载记录
            			contractDownloadLogRepository.save(contractDownloadLog);
            			//下载文件计量+1
            			contractDownloadCount.setCount(contractDownloadCount.getCount()+1);
            			contractDownloadCount.setLastDate(new Date());
            			contractDownloadCount.setGuide("1");
            			contractDownloadCountRepository.save(contractDownloadCount);
    			}
    		}
        }
		
		return result;
	}
	
	/**
	 * 创建文件附件
	 */
	public MimeBodyPart createAttachment(String filename ,String urlstr) throws Exception{
		MimeBodyPart attachmentPart = new MimeBodyPart();
	    URL url;
		try {
			url = new URL(urlstr);
			//通过截取url获取文件类型
			filename += urlstr.substring(0,urlstr.indexOf('?')).substring(urlstr.substring(0,urlstr.indexOf('?')).lastIndexOf("."));
		    attachmentPart.setDataHandler(new DataHandler(url));
		    attachmentPart.setFileName(MimeUtility.encodeText(filename));
		} catch (Exception e) {
			e.printStackTrace();
		}
        return attachmentPart;
	}

	/**
	 * 下载文件
	 */
	@Transactional
	@Override
	public void downloadFile(String userId,String id,HttpServletResponse response,String guide){
		OperatorContractBind contractBind = operatorContractDao.findContractInfo(id);
		if(contractBind != null){
			try{
				String fileName = contractBind.getTypename()+"-"+contractBind.getName();
				String urlstr = contractBind.getFile();
				//通过截取url获取文件类型
				fileName += urlstr.substring(0,urlstr.indexOf('?')).substring(urlstr.substring(0,urlstr.indexOf('?')).lastIndexOf("."));
				URL url = null;
				url = new URL(urlstr);
				response.reset();  
				response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'"+URLEncoder.encode(fileName, "UTF-8"));
				response.setHeader("Connection", "close");  
				response.setHeader("Content-Type", "application/octet-stream");
				HttpURLConnection connection = (HttpURLConnection)url.openConnection();
				BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
				OutputStream out = response.getOutputStream();
				int len = -1;
				byte[] b = new byte[1024*1024];
				while((len = is.read(b)) != -1 ){
					out.write(b, 0, len);
				}
				out.flush();
				out.close();
				is.close();
				
				//合同发送成功后		记录用户合同模板下载记录
		        PersonalUser user = personalUserRepository.findOne(userId);
		        if(user != null){
		        	//查找到用户后  添加用户合同模板下载计量
		        	if(guide==null||guide.equals("")){
		        		OperatorContractDownloadLog contractDownloadLog = new OperatorContractDownloadLog();
		        		contractDownloadLog.setUser(user);
		        		user.getDownloadLogs().add(contractDownloadLog);	//设置下载用户
		        		contractDownloadLog.setDate(new Date());	//设置下载日期
		        		OperatorContractDownloadCount contractDownloadCount = contractDownloadCountRepository.findByContractId(id).get(0);
		        		contractDownloadLog.setDownloadId(contractDownloadCount.getId());	//设置下载id
		        		//保存下载记录
		        		contractDownloadLogRepository.save(contractDownloadLog);
		        		//下载文件计量+1
		        		contractDownloadCount.setCount(contractDownloadCount.getCount()+1);
		        		contractDownloadCount.setLastDate(new Date());
		        		contractDownloadCountRepository.save(contractDownloadCount);
		        		
		        	}else{
		        		OperatorContractDownloadLog contractDownloadLog = new OperatorContractDownloadLog();
		        		contractDownloadLog.setUser(user);
		        		user.getDownloadLogs().add(contractDownloadLog);	//设置下载用户
		        		contractDownloadLog.setDate(new Date());	//设置下载日期
		        		contractDownloadLog.setGuide("1");
		        		OperatorContractDownloadCount contractDownloadCount = contractDownloadCountRepository.findByContractId(id).get(0);
		        		contractDownloadLog.setDownloadId(contractDownloadCount.getId());	//设置下载id
		        		//保存下载记录
		        		contractDownloadLogRepository.save(contractDownloadLog);
		        		//下载文件计量+1
		        		contractDownloadCount.setCount(contractDownloadCount.getCount()+1);
		        		contractDownloadCount.setLastDate(new Date());
		        		contractDownloadCount.setGuide("1");
		        		contractDownloadCountRepository.save(contractDownloadCount);
		        	
		        	}
		        	
		        }
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 合同模板下载计量查询
	 */
	@Override
	public Map<String, Object> getAllContractDownloadCounts(String name, String typeId,Integer pageSize,Integer currentPage,String guide) {
		/*Page<OperatorContractDownloadCount> pages = null;
		Pageable pageable = new PageRequest(currentPage, pageSize);
		name = name == null || name.equals("") ? "" : name;*/
		Map<String, Object>  map=new HashMap<>();
		if(guide==null||guide.equals("")){
			if(typeId == null || typeId.equals("")){
			//	pages = contractDownloadCountRepository.findAllByContractNameLikeAndGuideNotOrderByCountDesc(pageable, "%"+name+"%","1");
				String jpql = "select new guoanmaker.operator.business.modelnobind.OperatorContractDownloadCountBind(o.id, o.typeName, o.contractName, o.typeId,";
						jpql +="o.contractId, o.count,o.lastDate, o.guide) from OperatorContractDownloadCount o  where 1=1";
				jpql +=" and (o.guide !='1' or o.guide is NULL or o.guide='')";
				if(name!=null&&!name.equals("")){
					jpql+="and o.contractName like '%"+name+"%'";
				} 
				jpql += " order by o.count desc";
				if(currentPage==null){
					currentPage=0;
				}
				if (pageSize==null) {
					pageSize=10;
				}
				Query query = em.createQuery(jpql);
				List<OperatorContractDownloadCountBind> result = query.getResultList();
				map.put("totalElements", result.size());
				query.setFirstResult(currentPage*pageSize);
				query.setMaxResults(pageSize);
				List<OperatorContractDownloadCountBind> result1 = query.getResultList();
				map.put("content", result1);
			}else{
				//pages = contractDownloadCountRepository.findAllByContractNameLikeAndTypeIdAndGuideNotOrderByCountDesc(pageable, "%"+name+"%", typeId,"1");
				String jpql = "select new guoanmaker.operator.business.modelnobind.OperatorContractDownloadCountBind(o.id, o.typeName, o.contractName, o.typeId,";
				jpql +="o.contractId, o.count,o.lastDate, o.guide) from OperatorContractDownloadCount o  where 1=1";
				jpql +=" and (o.guide !='1' or o.guide is NULL or o.guide='')";
				if(name!=null&&!name.equals("")){
					jpql+=" and o.contractName like '%"+name+"%'";
				} 
				if(typeId!=null&&!typeId.equals("")){
					 jpql+=" and o.typeId='" + typeId + "' " ;
				}
				jpql += " order by o.count desc";
				if(currentPage==null){
					currentPage=0;
				}
				if (pageSize==null) {
					pageSize=10;
				}
				Query query = em.createQuery(jpql);
				List<OperatorContractDownloadCountBind> result = query.getResultList();
				map.put("totalElements", result.size());
				query.setFirstResult(currentPage*pageSize);
				query.setMaxResults(pageSize);
				List<OperatorContractDownloadCountBind> result1 = query.getResultList();
				map.put("content", result1);
			}
		}else{
			if(typeId == null || typeId.equals("")){
				//pages = contractDownloadCountRepository.findAllByContractNameLikeAndGuideEqualsOrderByCountDesc(pageable, "%"+name+"%","1");
				String jpql = "select new guoanmaker.operator.business.modelnobind.OperatorContractDownloadCountBind(o.id, o.typeName, o.contractName, o.typeId,";
				jpql +="o.contractId, o.count,o.lastDate, o.guide) from OperatorContractDownloadCount o  where 1=1";
				jpql +=" and o.guide ='1'";
				if(name!=null&&!name.equals("")){
					jpql+="and o.contractName like '%"+name+"%'";
				} 
				jpql += " order by o.count desc";
				if(currentPage==null){
					currentPage=0;
				}
				if (pageSize==null) {
					pageSize=10;
				}
				Query query = em.createQuery(jpql);
				List<OperatorContractDownloadCountBind> result = query.getResultList();
				map.put("totalElements", result.size());
				query.setFirstResult(currentPage*pageSize);
				query.setMaxResults(pageSize);
				List<OperatorContractDownloadCountBind> result1 = query.getResultList();
				map.put("content", result1);
			
			}else{
				String jpql = "select new guoanmaker.operator.business.modelnobind.OperatorContractDownloadCountBind(o.id, o.typeName, o.contractName, o.typeId,";
				jpql +="o.contractId, o.count,o.lastDate, o.guide) from OperatorContractDownloadCount o  where 1=1";
				jpql +=" and o.guide ='1'";
				if(name!=null&&!name.equals("")){
					jpql+="and o.contractName like '%"+name+"%'";
				} 
				if(typeId!=null&&!typeId.equals("")){
					 jpql+=" and o.typeId='" + typeId + "' " ;
				}
				jpql += " order by o.count desc";
				if(currentPage==null){
					currentPage=0;
				}
				if (pageSize==null) {
					pageSize=10;
				}
				Query query = em.createQuery(jpql);
				List<OperatorContractDownloadCountBind> result = query.getResultList();
				map.put("totalElements", result.size());
				query.setFirstResult(currentPage*pageSize);
				query.setMaxResults(pageSize);
				List<OperatorContractDownloadCountBind> result1 = query.getResultList();
				map.put("content", result1);
				//pages = contractDownloadCountRepository.findAllByContractNameLikeAndTypeIdAndGuideEqualsOrderByCountDesc(pageable, "%"+name+"%", typeId,"1");
			}
		}
		return map;
	}

	/**
	 * 合同模板下载历史记录查询
	 */
	@Override
	public Page<OperatorContractDownloadLog> getAllContractDownloadLogs(String id,Integer pageSize,Integer currentPage,String guide) {
		Pageable pageable = new PageRequest(currentPage, pageSize);
		if(guide==null||guide.equals("")){
			return contractDownloadLogRepository.findAllByDownloadIdAndGuideIsNullOrderByDateDesc(pageable, id);
		}else{
			return contractDownloadLogRepository.findAllByDownloadIdAndGuideEqualsOrderByDateDesc(pageable, id,"1");
		}
	}
	
}
